var express = require('express')
    , router = express.Router()
    , logger = require('log4js').getLogger('log.index.js');

var urlLog = require('../../model').urlLog;

router.use((req, res, next) => {
    logger.info(req.url);
    next();
});

router.get('/', (req, res) => {
    res.send(['/urlLog']);
});

router.get('/urlLog', (req, res) => {
    var query = req.query;
    var order = ~~query.order || -1,
        record = ~~query.record || 10,
        page = ~~query.page || 1,
        begin = ~~query.begin || 0;
    
    if (isNaN(order)) {
        order = -1;
    }

    var paginations = {
        page: page,
        record: record
    };

    urlLog.count((err, cou) => {
        if (err) return res.send(err);
        console.log(err, cou);

        paginations.count = cou;
        paginations.pages = Math.ceil(cou / record);
        urlLog.find({}, '-_id').sort({ $natural: order }).skip((page - 1) * record).limit(record).exec((err, rel) => {
            if (err) return res.send(err);
            res.send({ rel, paginations });
        });
    });
});

module.exports = router;